﻿using Newtonsoft.Json;
using RestSharp;
using System;
using System.Collections.Generic;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Security.Cryptography;
using System.Text;
using System.Threading.Tasks;

namespace MyOCR.Picture
{
    //https://deepi.sogou.com/
    class SouGo_PictureHandleOCR :PictureHandle
    {
        string service = "basicOpenOcr";
        string salt = "1508404016012";
        string imageShort;
        private SetUpSave _setUpSave;

        public SouGo_PictureHandleOCR()
        {
            _setUpSave = SetUpSave.Create();

        }

        protected override string getSign()
        {
            string sign = string.Format("{0}{1}{2}{3}{4}", _setUpSave.SouGou_Pid, service, salt, imageShort.Substring(0,1024), _setUpSave.SouGou_Key);
            var md5 = new MD5CryptoServiceProvider();
            var result = Encoding.UTF8.GetBytes(sign);
            var output = md5.ComputeHash(result);

            return BitConverter.ToString(output).Replace("-", "").ToLower();
        }

        public override string IdentifyImage(Image img)
        {
            var client = new RestClient("http://deepi.sogou.com/api/sogouService");
            var request = new RestRequest(Method.POST);
            
            request.Timeout = 10000;
            request.AddHeader("cache-control", "no-cache");
            request.AddHeader("accept", "application/json");
            request.AddHeader("content-type", "application/x-www-form-urlencoded; charset=UTF-8");
            
            // base64 string file picture,too long in the case we will omit string
            var bmp = GrayscaleImage(img);
            imageShort = ImageToBase64(bmp);
        
            string sign = getSign();
            //string lang = InterfaceAndLanguage.dic["搜狗"][Program._config._Language];
            //request.AddParameter("lang", "auto");
            request.AddParameter("pid", _setUpSave.SouGou_Pid);
            request.AddParameter("service", service);
            request.AddParameter("sign", sign);
            request.AddParameter("salt", salt);
            request.AddParameter("image", imageShort);
            IRestResponse response = client.Execute(request);

            //解析获取的json
            var lst = new List<string>();
            var content = response.Content;
            dynamic json = JsonConvert.DeserializeObject(content);
            foreach (var item in json.result)
            {
                lst.Add(item.content.ToString());
            }
            return string.Join("\r\n", lst);
        }

        /// <summary>
        /// 将图片转换为base64
        /// </summary>
        /// <param name="bmp"></param>
        /// <returns></returns>
        private string ImageToBase64(Bitmap bmp)
        {
            MemoryStream ms = new MemoryStream();
            bmp.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg);
            byte[] arr = new byte[ms.Length];
            ms.Position = 0;
            ms.Read(arr, 0, (int)ms.Length);
            ms.Close();
            string image = Convert.ToBase64String(arr);
            return image;
        }
    }
}
